package com.kpmg.datalake.common.service.impl;

import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDS;
import com.kpmg.datalake.common.model.DimInfo;
import com.kpmg.datalake.common.service.BaseInfoService;
import com.kpmg.datalake.common.service.RbacDataService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Echo
 * @create 2018-07-12
 * @desc
 */
@Service
public class RbacDataServiceImpl implements RbacDataService {

    @Autowired
    private BaseInfoService baseInfoService;

    /**
     *
     * @param projectId 项目id
     * @return
     */
    @Override
    @DynamicDS("projectId")
    public DimInfo getDataMenuList(String projectId) {

        PageInfo<DimInfo> corp = baseInfoService.initCorp(0, -1, projectId, null);

        List<DimInfo> result = corp.getList();

        DimInfo compayTree = new DimInfo();
        // 设置顶级实体公司
        compayTree.setCode(result.get(0).getCode());
        compayTree.setValue(result.get(0).getValue());
        compayTree.setLevel(result.get(0).getLevel());
        compayTree.setParentCode("");

        // 递归设置子公司
        compayTree.setChildList(getChild(compayTree.getCode(), result));

        return compayTree;
    }

    /**
     * 递归查找子菜单
     *
     * @param id       当前菜单id
     * @param rootMenu 要查找的列表
     * @return
     */
    private List<DimInfo> getChild(String id, List<DimInfo> rootMenu) {
        // 子菜单
        List<DimInfo> childList = new ArrayList<>();
        for (DimInfo menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StringUtils.isNotBlank(menu.getParentCode()) && menu.getParentCode().equals(id)) {
                childList.add(menu);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (DimInfo menu : childList) {
            menu.setChildList(getChild(menu.getCode(), rootMenu));
        } // 递归退出条件
        if (childList.isEmpty()) {
            return childList;
        }
        return childList;
    }
}
